using System;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace BanZuiCloudControlAgent.Utils.Common
{
    /// <summary>
    /// 简化版配置服务，只提供基本的配置读写功能
    /// </summary>
    public class ConfigurationService
    {
        private static readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
        private Dictionary<string, object> _configData;
        private string _configFilePath;
        private static ConfigurationService _instance;
        private static readonly object _lockObject = new object();
        
        // 配置根目录常量
        private const string CONFIG_ROOT_DIRECTORY = @"C:\脚本配置文件\云控系统配置";
        private const string CONFIG_FILES_DIRECTORY = @"Config";

        /// <summary>
        /// 获取ConfigurationService的单例实例
        /// </summary>
        public static ConfigurationService Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lockObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new ConfigurationService();
                        }
                    }
                }
                return _instance;
            }
        }

        /// <summary>
        /// 私有构造函数，确保单例模式
        /// </summary>
        private ConfigurationService()
        {
            try
            {
                // 设置配置文件路径
                string configDir = Path.Combine(CONFIG_ROOT_DIRECTORY, CONFIG_FILES_DIRECTORY);
                _configFilePath = Path.Combine(configDir, "appsettings.json");
                
                // 确保目录存在
                if (!Directory.Exists(configDir))
                {
                    Directory.CreateDirectory(configDir);
                }
                
                _configData = new Dictionary<string, object>();
                LoadConfig();
                
                _logger.Info($"配置服务初始化完成，配置文件路径: {_configFilePath}");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "配置服务初始化失败");
                _configData = new Dictionary<string, object>();
                
                // 确保UI配置存在
                _configData["UI"] = JObject.FromObject(new UISettings());
            }
        }

        /// <summary>
        /// 加载配置
        /// </summary>
        private void LoadConfig()
        {
            try
            {
                if (File.Exists(_configFilePath))
                {
                    string json = File.ReadAllText(_configFilePath);
                    _configData = JsonConvert.DeserializeObject<Dictionary<string, object>>(json) 
                        ?? new Dictionary<string, object>();
                    _logger.Info("配置文件加载成功");
                }
                else
                {
                    _logger.Info("配置文件不存在，将使用默认配置");
                    _configData = new Dictionary<string, object>();
                }
                
                // 确保UI配置存在
                if (!_configData.ContainsKey("UI"))
                {
                    _configData["UI"] = JObject.FromObject(new UISettings());
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "加载配置文件失败");
                _configData = new Dictionary<string, object>();
                
                // 确保UI配置存在
                _configData["UI"] = JObject.FromObject(new UISettings());
            }
        }

        /// <summary>
        /// 保存配置到文件
        /// </summary>
        public void SaveConfig()
        {
            try
            {
                // 确保目录存在
                string directory = Path.GetDirectoryName(_configFilePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                
                string json = JsonConvert.SerializeObject(_configData, Formatting.Indented);
                File.WriteAllText(_configFilePath, json);
                _logger.Info("配置已保存到文件");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "保存配置文件失败");
            }
        }

        /// <summary>
        /// 重新加载配置
        /// </summary>
        public void ReloadConfig()
        {
            LoadConfig();
        }

        /// <summary>
        /// 获取配置节
        /// </summary>
        /// <typeparam name="T">配置类型</typeparam>
        /// <param name="sectionName">节名称</param>
        /// <returns>配置对象</returns>
        public T GetSection<T>(string sectionName) where T : class, new()
        {
            try
            {
                if (_configData.ContainsKey(sectionName) && _configData[sectionName] != null)
                {
                    if (_configData[sectionName] is JObject jObject)
                    {
                        return jObject.ToObject<T>();
                    }
                    else if (_configData[sectionName] is Dictionary<string, object> dictSection)
                    {
                        string json = JsonConvert.SerializeObject(dictSection);
                        return JsonConvert.DeserializeObject<T>(json);
                    }
                }
                return new T();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"获取配置节失败: {sectionName}");
                return new T();
            }
        }

        /// <summary>
        /// 获取配置值
        /// </summary>
        /// <param name="key">配置键，支持"Section:Key"格式</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置值</returns>
        public string GetValue(string key, string defaultValue = null)
        {
            try
            {
                // 处理"Section:Key"格式
                string[] parts = key.Split(new[] { ':' }, 2);
                if (parts.Length > 1)
                {
                    return GetNestedValue<string>(parts[0], parts[1], defaultValue);
                }
                
                if (_configData.ContainsKey(key) && _configData[key] != null)
                {
                    return _configData[key].ToString();
                }
                return defaultValue;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"获取配置值失败: {key}");
                return defaultValue;
            }
        }

        /// <summary>
        /// 获取类型化配置值
        /// </summary>
        /// <typeparam name="T">值类型</typeparam>
        /// <param name="key">配置键，支持"Section:Key"格式</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置值</returns>
        public T GetValue<T>(string key, T defaultValue = default)
        {
            try
            {
                // 处理"Section:Key"格式
                string[] parts = key.Split(new[] { ':' }, 2);
                if (parts.Length > 1)
                {
                    return GetNestedValue<T>(parts[0], parts[1], defaultValue);
                }
                
                if (_configData.ContainsKey(key) && _configData[key] != null)
                {
                    return (T)Convert.ChangeType(_configData[key], typeof(T));
                }
                return defaultValue;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"获取类型化配置值失败: {key}");
                return defaultValue;
            }
        }

        /// <summary>
        /// 获取嵌套的配置值
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="section">配置节</param>
        /// <param name="key">配置键</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置值</returns>
        public T GetNestedValue<T>(string section, string key, T defaultValue = default)
        {
            try
            {
                if (_configData.ContainsKey(section) && _configData[section] != null)
                {
                    Dictionary<string, object> sectionData;
                    
                    if (_configData[section] is JObject jObject)
                    {
                        sectionData = jObject.ToObject<Dictionary<string, object>>();
                    }
                    else if (_configData[section] is Dictionary<string, object> dictSection)
                    {
                        sectionData = dictSection;
                    }
                    else
                    {
                        return defaultValue;
                    }
                    
                    if (sectionData.ContainsKey(key) && sectionData[key] != null)
                    {
                        if (sectionData[key] is JValue jValue)
                        {
                            return jValue.ToObject<T>();
                        }
                        return (T)Convert.ChangeType(sectionData[key], typeof(T));
                    }
                }
                return defaultValue;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"获取嵌套配置值失败: {section}.{key}");
                return defaultValue;
            }
        }

        /// <summary>
        /// 设置配置值
        /// </summary>
        /// <param name="key">配置键，支持"Section:Key"格式</param>
        /// <param name="value">配置值</param>
        public void SetValue(string key, object value)
        {
            try
            {
                // 处理"Section:Key"格式
                string[] parts = key.Split(new[] { ':' }, 2);
                if (parts.Length > 1)
                {
                    SetNestedValue(parts[0], parts[1], value);
                    return;
                }
                
                _configData[key] = value;
                SaveConfig();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"设置配置值失败: {key}");
            }
        }

        /// <summary>
        /// 设置嵌套的配置值
        /// </summary>
        /// <param name="section">配置节</param>
        /// <param name="key">配置键</param>
        /// <param name="value">配置值</param>
        public void SetNestedValue(string section, string key, object value)
        {
            try
            {
                // 确保节存在
                if (!_configData.ContainsKey(section))
                {
                    _configData[section] = new Dictionary<string, object>();
                }
                
                // 获取或创建节
                Dictionary<string, object> sectionData;
                if (_configData[section] is JObject jObject)
                {
                    sectionData = jObject.ToObject<Dictionary<string, object>>();
                }
                else if (_configData[section] is Dictionary<string, object> dictSection)
                {
                    sectionData = dictSection;
                }
                else
                {
                    sectionData = new Dictionary<string, object>();
                }
                
                // 设置值
                sectionData[key] = value;
                _configData[section] = sectionData;
                
                // 保存配置
                SaveConfig();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"设置嵌套配置[{section}.{key}]失败: {ex.Message}");
            }
        }


    }
} 